<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>投资资产走势图</title>
    <script src="../assets/js/echarts.js"></script>
    <script src="../assets/js/util.js"></script>
    <link rel="stylesheet" href="../assets/css/common.css" />
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>投资资产走势图</h1>
            <p class="subtitle">可视化您的投资增长历程</p>
        </div>

        <div class="config-panel">
            <div class="config-row">
                <div class="config-item">
                    <label for="stock-name">股票名称</label>
                    <input type="text" id="stock-name" value="紫金矿业">
                </div>
                <div class="config-item">
                    <label for="stock-code">股票代码</label>
                    <input type="text" id="stock-code" value="601899">
                </div>
                <div class="config-item">
                    <label for="start-date">开始日期</label>
                    <input type="date" id="start-date" value="2022-01-01">
                </div>
                <div class="config-item">
                    <label for="end-date">结束日期</label>
                    <input type="date" id="end-date" value="2025-09-01">
                </div>
                <div class="config-item">
                    <label for="investment-amount">投资金额(元)</label>
                    <input type="number" id="investment-amount" value="1000000">
                </div>
                <div class="config-item">
                    <label for="animation-speed">动画速度</label>
                    <input type="range" id="animation-speed" min="10" max="500" value="150">
                </div>
            </div>
            <div class="config-row">
                <div class="config-item">
                    <label for="stock-name-color">股票名称颜色</label>
                    <input type="color" id="stock-name-color" value="#ff4757">
                </div>
                <div class="config-item">
                    <label for="line-color">折线颜色</label>
                    <input type="color" id="line-color" value="#FFD700">
                </div>
                <div class="config-item">
                    <label for="shadow-opacity">阴影透明度</label>
                    <input type="range" id="shadow-opacity" min="0" max="100" value="30">
                </div>
                <div class="config-item">
                    <label for="chart-bg-color">图表背景色</label>
                    <input type="color" id="chart-bg-color" value="#000000">
                </div>
                <div class="config-item">
                    <label for="info-panel-color">总资产背景色</label>
                    <input type="color" id="info-panel-color" value="#000000">
                </div>
                <div class="config-item">
                    <label for="page-bg-color">网页背景色</label>
                    <input type="color" id="page-bg-color" value="#1a2a6c">
                </div>
            </div>
            <div class="config-row">
                <button class="btn" onclick="applyConfig()">应用配置</button>
            </div>
        </div>
        <br>
        <br>
        <br>

        <div class="info-panel" id="info-panel">
            <div>当前总资产</div>
            <div id="current-value" class="current-value">¥1,000,000</div>
            <div id="profit-loss-info"></div>
        </div>

        <div class="text-panel">
            <div class="text-line-1" id="investment-text">假如2022年买入100万</div>
            <div class="text-line-2" id="date-range-text">截至2025-09-01后复权</div>
            <div class="text-line-3" id="stock-name-text">紫金矿业</div>
        </div>

        <div class="chart-container" id="chart-container-wrapper">
            <div id="chart-container" style="width: 100%; height: 100%;"></div>
            <div id="loading" class="loading">数据加载中...</div>
        </div>
        <div class="text-panel">
            <div class="text-line-4">理财有风险，投资需谨慎</div>
        </div>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <div class="instructions">
            <p>点击图表可暂停/继续动画 | 按空格键暂停/继续 | 按R键重新开始</p>
        </div>

        <div class="controls">
            <button class="btn" onclick="toggleAnimation()">暂停/继续</button>
            <button class="btn" onclick="resetAnimation()">重新开始</button>
        </div>
    </div>

    <script>
        // ================== 全局变量 ==================
        let myChart;
        let rawData = [];
        let animatedData = [];
        let currentIndex = 0;
        let animationInterval;
        let animationSpeed = 300;
        let investmentAmount = 1000000;
        let isAnimationComplete = false;
        let stockCode = '601899';
        let stockName = '紫金矿业';
        let startDate = '2022-01-01';
        let endDate = '2025-09-01';
        let stockNameColor = '#ff4757';
        let lineColor = '#FFD700';
        let chartBgColor = '#000000';
        let infoPanelColor = '#000000';
        let pageBgColor = '#1a2a6c';
        let shadowOpacity = 30;

        // ================== 入口 ==================
        function init() {
            initializeChart();
            updateTextElements(); // 初始化文本显示
            updateColors(); // 初始化颜色
            loadData();
            setupEventListeners();
        }

        // ================== 更新文本元素 ==================
        function updateTextElements() {
            // 从输入框获取最新配置
            stockName = document.getElementById('stock-name').value;
            investmentAmount = parseInt(document.getElementById('investment-amount').value) || 1000000;
            startDate = document.getElementById('start-date').value;
            endDate = document.getElementById('end-date').value;

            // 格式化投资金额显示
            const formattedAmount = (investmentAmount / 10000).toFixed(0);

            // 更新文本元素
            document.getElementById('investment-text').textContent =
                `假如${startDate.substring(0, 4)}年买入${formattedAmount}万`;
            document.getElementById('date-range-text').textContent =
                `截至${endDate}后复权`;
            document.getElementById('stock-name-text').textContent = stockName;
        }

        // ================== 更新颜色配置 ==================
        function updateColors() {
            // 从输入框获取颜色配置
            stockNameColor = document.getElementById('stock-name-color').value;
            lineColor = document.getElementById('line-color').value;
            chartBgColor = document.getElementById('chart-bg-color').value;
            infoPanelColor = document.getElementById('info-panel-color').value;
            pageBgColor = document.getElementById('page-bg-color').value;
            shadowOpacity = parseInt(document.getElementById('shadow-opacity').value);

            // 应用颜色配置
            document.getElementById('stock-name-text').style.color = stockNameColor;
            document.getElementById('chart-container-wrapper').style.backgroundColor = chartBgColor;
            document.getElementById('info-panel').style.backgroundColor = infoPanelColor;

            // 设置网页背景
            document.body.style.background = pageBgColor;

            // 更新图表颜色
            if (myChart) {
                const shadowAlpha = (shadowOpacity / 100).toFixed(2);
                const areaAlpha = (shadowOpacity / 100 * 0.3).toFixed(2);

                myChart.setOption({
                    series: [{
                        lineStyle: {
                            color: lineColor,
                            shadowColor: lineColor
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: hexToRgba(lineColor, areaAlpha)
                                }, {
                                    offset: 1,
                                    color: hexToRgba(lineColor, 0)
                                }]
                            }
                        }
                    }]
                });
            }
        }

        // ================== 图表初始化 ==================
        function initializeChart() {
            const chartDom = document.getElementById('chart-container');
            myChart = echarts.init(chartDom);

            const shadowAlpha = (shadowOpacity / 100).toFixed(2);
            const areaAlpha = (shadowOpacity / 100 * 0.3).toFixed(2);

            const option = {
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(0,0,0,.9)',
                    borderColor: '#FFD700',
                    borderWidth: 1,
                    textStyle: { color: '#fff', fontSize: 16 },
                    formatter: (params) => {
                        const item = params[0];
                        return `日期: ${item.name}<br/>总资产: ¥${item.value.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    top: '15%',  // 上方多留空间
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    axisLine: {
                        lineStyle: { color: '#FFFFFF', width: 2 }
                    },
                    axisLabel: {
                        rotate: 45,
                        color: '#FFFFFF',
                        fontSize: 12,
                        margin: 15
                    },
                    axisTick: {
                        alignWithLabel: true,
                        lineStyle: { color: '#FFFFFF' }
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: { color: '#FFFFFF', width: 2 }
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: 'rgba(255,255,255,0.2)'
                        }
                    },
                    axisLabel: {
                        color: '#FFFFFF',
                        fontSize: 14,
                        formatter: function(value) {
                            if (value >= 1000000) {
                                return '¥' + (value / 1000000).toFixed(2) + 'M';
                            }
                            return '¥' + value;
                        }
                    }
                },
                series: [{
                    name: '总资产',
                    type: 'line',
                    data: [],
                    showSymbol: false,
                    smooth: true,
                    lineStyle: {
                        width: 4,
                        color: lineColor,
                        shadowBlur: 15,
                        shadowColor: hexToRgba(lineColor, shadowAlpha)
                    },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: hexToRgba(lineColor, areaAlpha)
                            }, {
                                offset: 1,
                                color: hexToRgba(lineColor, 0)
                            }]
                        }
                    }
                }],
                backgroundColor: 'rgba(0,0,0,0.1)'
            };

            myChart.setOption(option);
        }

        // ================== 数据加载 ==================
        async function loadData() {
            try {
                document.getElementById('loading').style.display = 'block';

                // 从输入框获取最新配置
                stockCode = document.getElementById('stock-code').value;
                startDate = document.getElementById('start-date').value;
                endDate = document.getElementById('end-date').value;
                investmentAmount = parseInt(document.getElementById('investment-amount').value) || 1000000;
                animationSpeed = 550 - parseInt(document.getElementById('animation-speed').value);

                // 更新文本显示和颜色
                updateTextElements();
                updateColors();

                // 使用您的API端点
                // const apiUrl = `http://127.0.0.1:8888/api/stock/daily?symbol=${stockCode}&start_date=${startDate}&end_date=${endDate}`;
                const apiUrl = `http://127.0.0.1:8888/api/stock/daily`;

                const res = await fetch(apiUrl,{
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({"ts_code": addSuffix(stockCode),"start_date":formatDateToNumber(startDate),"end_date":formatDateToNumber(endDate),"adi":"1"})
                });
                if (!res.ok) throw new Error('网络错误，无法获取数据');

                const json = await res.json();
                if (json.code !== 0) throw new Error(json.msg || 'API返回错误');

                if (!json.data || json.data.length === 0) {
                    throw new Error('API返回数据为空');
                }

                // 计算总资产
                const originalData = json.data.reverse();
                const initialPrice = originalData[0].close;
                rawData = originalData.map((item) => ({
                    date: formatDate(item.trade_date),
                    total: (item.close / initialPrice) * investmentAmount
                }));

                document.getElementById('loading').style.display = 'none';

                animatedData = [rawData[0]];
                updateChartDisplay();
                updateInfoPanel();

                // 自动开始动画
                setTimeout(() => startAnimation(), 1000);

            } catch (err) {
                document.getElementById('loading').innerHTML =
                    `<span class="error">加载失败: ${err.message}</span>`;
                document.getElementById('current-value').textContent = '加载失败';
                document.getElementById('current-value').style.color = '#ff4757';
            }
        }

        // 应用配置
        function applyConfig() {
            // 停止当前动画
            clearInterval(animationInterval);
            animationInterval = null;

            // 重置状态
            rawData = [];
            animatedData = [];
            currentIndex = 0;
            isAnimationComplete = false;

            // 重新加载数据
            loadData();
        }

        // 计算动态Y轴范围
        function calculateDynamicYAxisRange(data) {
            if (data.length === 0) return { min: 0, max: 100000 };

            const values = data.map(d => d.total);
            const minValue = Math.min(...values);
            const maxValue = Math.max(...values);

            // 添加一些边距，上方多留空间
            const range = maxValue - minValue;
            const marginBottom = range * 0.1;
            const marginTop = range * 0.3; // 上方多留空间

            return {
                min: Math.floor(minValue - marginBottom),
                max: Math.ceil(maxValue + marginTop)
            };
        }

        // ================== 图表更新 ==================
        function updateChartDisplay() {
            let displayData;
            let xAxisData;
            let yAxisConfig;

            if (isAnimationComplete) {
                // 动画完成：显示全部数据
                displayData = animatedData;
                xAxisData = animatedData.map(d => d.date);
                yAxisConfig = {
                    min: null,
                    max: null
                };
            } else {
                // 动画中：显示最近10条数据
                const recentData = getRecent10Data(animatedData);
                displayData = recentData;
                xAxisData = recentData.map(d => d.date);

                // 动态计算Y轴范围，上方多留空间
                const yRange = calculateDynamicYAxisRange(recentData);
                yAxisConfig = {
                    min: yRange.min,
                    max: yRange.max
                };
            }

            const chartData = displayData.map(d => ({
                name: d.date,
                value: d.total
            }));

            myChart.setOption({
                xAxis: {
                    data: xAxisData,
                    axisLabel: {
                        interval: isAnimationComplete ? 'auto' : 0
                    }
                },
                yAxis: yAxisConfig,
                series: [{
                    data: chartData,
                    smooth: !isAnimationComplete
                }]
            });
        }

        // ================== 信息面板 ==================
        function updateInfoPanel() {
            if (!animatedData.length) return;

            const cur = animatedData[animatedData.length - 1];
            const currentValue = cur.total;

            document.getElementById('current-value').textContent =
                '¥' + currentValue.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',');

            // 根据盈亏改变颜色
            const isProfit = currentValue > investmentAmount;
            document.getElementById('current-value').style.color = isProfit ? '#ff4757' : '#FFD700';

            // 更新盈亏信息
            const profitLoss = currentValue - investmentAmount;
            const percentChange = ((profitLoss / investmentAmount) * 100).toFixed(2);
            const profitLossInfo = document.getElementById('profit-loss-info');

            if (profitLoss !== 0) {
                profitLossInfo.innerHTML =
                    `${profitLoss >= 0 ? '盈利' : '亏损'}: ¥${Math.abs(profitLoss).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')} (${percentChange}%)`;
                profitLossInfo.style.color = profitLoss >= 0 ? '#ff4757':'#00b894';
            } else {
                profitLossInfo.innerHTML = '';
            }
        }

        // ================== 动画控制 ==================
        function startAnimation() {
            if (currentIndex >= rawData.length) {
                completeAnimation();
                return;
            }

            clearInterval(animationInterval);

            animationInterval = setInterval(() => {
                if (currentIndex >= rawData.length) {
                    completeAnimation();
                    return;
                }

                animatedData.push(rawData[currentIndex]);
                updateChartDisplay();
                updateInfoPanel();
                currentIndex++;

            }, animationSpeed);

        }

        // 动画完成处理
        function completeAnimation() {
            clearInterval(animationInterval);
            isAnimationComplete = true;

            // 切换到完整视图
            updateChartDisplay();

            // 添加完成提示
            const finalValue = animatedData[animatedData.length - 1].total;
            const profitLoss = finalValue - investmentAmount;
            const percentChange = ((profitLoss / investmentAmount) * 100).toFixed(2);

            const profitLossInfo = document.getElementById('profit-loss-info');
            profitLossInfo.innerHTML =
                `最终${profitLoss >= 0 ? '盈利' : '亏损'}: ¥${Math.abs(profitLoss).toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')} (${percentChange}%)`;
            profitLossInfo.style.color = profitLoss >= 0 ? '#ff4757' : '#00b894';
            profitLossInfo.style.fontSize = '1.2rem';

            // 不再自动重新开始动画
        }

        // 重置动画
        function resetAnimation() {
            clearInterval(animationInterval);
            animatedData = [rawData[0]];
            currentIndex = 1;
            isAnimationComplete = false;

            // 移除完成提示的样式
            const profitLossInfo = document.getElementById('profit-loss-info');
            profitLossInfo.style.fontSize = '';

            updateChartDisplay();
            updateInfoPanel();
            startAnimation();
        }

        // 切换动画状态
        function toggleAnimation() {
            if (isAnimationComplete) return;

            if (animationInterval) {
                clearInterval(animationInterval);
                animationInterval = null;
            } else {
                startAnimation();
            }
        }

        // ================== 事件绑定 ==================
        function setupEventListeners() {
            // 窗口大小变化时重绘图表
            window.addEventListener('resize', () => {
                if (myChart) {
                    myChart.resize();
                }
            });

            // 点击图表区域暂停/继续
            const chartDom = document.getElementById('chart-container');
            chartDom.addEventListener('click', () => {
                if (isAnimationComplete) {
                    return;
                } else if (animationInterval) {
                    clearInterval(animationInterval);
                    animationInterval = null;
                } else {
                    startAnimation();
                }
            });

            // 键盘控制
            document.addEventListener('keydown', (e) => {
                if (e.code === 'Space') {
                    e.preventDefault();
                    if (isAnimationComplete) return;
                    if (animationInterval) {
                        clearInterval(animationInterval);
                        animationInterval = null;
                    } else {
                        startAnimation();
                    }
                } else if (e.code === 'KeyR') {
                    e.preventDefault();
                    resetAnimation();
                }
            });

            // 颜色选择器变化时实时更新
            document.getElementById('stock-name-color').addEventListener('input', updateColors);
            document.getElementById('line-color').addEventListener('input', updateColors);
            document.getElementById('chart-bg-color').addEventListener('input', updateColors);
            document.getElementById('info-panel-color').addEventListener('input', updateColors);
            document.getElementById('page-bg-color').addEventListener('input', updateColors);
            document.getElementById('shadow-opacity').addEventListener('input', updateColors);
        }

        // ================== 页面启动 ==================
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>